package com.njupt.Tree;



import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/20 10:00
 * @Description: 二叉树的层次遍历
 * @Version: 1.0
 */


public class LevelOrder {

    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<List<Integer>> results = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        if(root == null) return results;
        queue.addLast(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> result = new ArrayList<>();
            for (int i = 0; i < size; i++) {

                TreeNode treeNode = queue.pollFirst();
                result.add(treeNode.val);
                if(treeNode.left != null) queue.addLast(treeNode.left);
                if(treeNode.right != null) queue.addLast(treeNode.right);
            }
            results.add(result);
        }
        return results;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        LevelOrder test = new LevelOrder();
        List<List<Integer>> lists = test.levelOrder(root);
        System.out.println(lists);

    }
}
